<template>
  <div
    class="carbox fixed bottom-100rpx left-0 right-0 top-0 z-9 box-border max-h-screen w-100% overflow-y-auto pb-140rpx pt-40%"
    @click.stop="closeDlalog">
    <div
      class="teaGoodsCar cardBoxShaow scrolldemo fixed bottom-160rpx left-0 right-0 z-9999 m-32rpx box-border max-h-700rpx min-h-0 rounded-48rpx bg-hex-ffffff"
      @click.stop>
      <div
        class="sticky left-0 right-0 top-0 z-9 box-border flex items-center justify-between border-2rpx border-transparent border-b-hex-F5F5F5 border-solid bg-hex-ffffff px-32rpx py-28rpx">
        <div class="flex">
          <div class="h-77rpx w-77rpx flex items-center justify-center" @click.stop="handleInver">
            <image
              v-if="invertShow"
              :src="`${cdnUrl}/svgicons/userComment/select.svg${imgVersion}`"
              mode="scaleToFill"
              class="h-50rpx w-50rpx"

            />
            <div v-if="!invertShow" class="h-40rpx w-40rpx border-4rpx border-hex-ABCD03 rounded-50% border-solid" />
          </div>
          <text class="mt-12rpx font-600">茶饮口袋</text>
        </div>
        <div class="flex items-center" @click.stop="opendelpop">
          <image
            :src="`${cdnUrl}/svgicons/search/del.svg${imgVersion}`"
            mode="scaleToFill"
            class="h-50rpx w-50rpx"
          />
        </div>
      </div>
      <div class="mb-34rpx">
        <uni-swipe-action>
          <uni-swipe-action-item
            v-for="(item, index) in propsDataList"
            :key="index"
            :right-options="options2"
            @change="swipeChange($event, index)"
            @click.stop="swipeClick($event, item.itemId)"
          >
            <div
              class="box-border flex items-center p-32rpx"
            >
              <div class="h-77rpx w-77rpx flex items-center justify-center">
                <image
                  v-if="item.selectStatus===0"
                  :src="`${cdnUrl}/svgicons/userComment/select.svg${imgVersion}`"
                  mode="scaleToFill"
                  class="h-50rpx w-50rpx"
                  @click="handleCancelSelect(item.itemId)"
                />
                <div
                  v-if="item.selectStatus===1"
                  class="h-40rpx w-40rpx border-4rpx border-hex-ABCD03 rounded-50% border-solid"
                  @click="handleSelect(item.itemId)" />
              </div>
              <div 
                class="relative mr-3% mt-24rpx h-180rpx w-180rpx overflow-hidden rounded-16rpx">
                <image
                  class="absolute left-50% top-50% h-180rpx w-180rpx rounded-16rpx"
                  style="transform: translate(-50%, -50%);" :src="item.itemImage" mode="aspectFill" />
              </div>
              <div class="w-65%">
                <div class="mb-8rpx text-28rpx font-600 text-hex-333333">{{ item.itemName }}</div>
                <div class="mb-12rpx flex items-center text-24rpx text-hex-7c8699">
                  <!-- <div
                    v-for="itm in item.tagList"
                    class="tagLine relative mr-20rpx">{{ itm }}</div> -->
                  <div>{{ item.specsDesc }}</div>
                </div>
                <div class="flex items-center justify-between">
                  <div class="text-28rpx font-bold text-hex-333333">¥{{ item.unitPrice }}</div>
                  <div class="flex items-center">
                    <image
                      :src="`${cdnUrl}/svgicons/userComment/down.svg${imgVersion}`"
                      mode="scaleToFill"
                      class="mt-5rpx h-50rpx w-50rpx"
                      @click="reduceGoodsNum(item.itemId, item.amount)"
                    />
                    <div class="ml-20rpx mr-20rpx">{{ item.amount }}</div>
                    <image
                      :src="`${cdnUrl}/svgicons/userComment/add.svg${imgVersion}`"
                      mode="scaleToFill"
                      class="mt-5rpx h-50rpx w-50rpx"
                      @click="addGoodsNum(item.itemId)"
                    />
                  </div>
                </div>
              </div>
            </div>
          </uni-swipe-action-item>
        </uni-swipe-action>
        <uni-swipe-action>
          <uni-swipe-action-item
            v-for="(item, index) in freezeGoodsList"
            :key="index"
            :right-options="options2"
            @change="swipeChange($event, index)"
            @click.stop="swipeClick($event, item.itemId)"
          >
            <div
              class="box-border flex items-center p-32rpx"
            >
              <div class="h-77rpx w-77rpx flex items-center justify-center">
                <div
                  class="h-40rpx w-40rpx border-4rpx border-hex-E0E0E0 rounded-50% border-solid" />
              </div>
              <div class="mr-24rpx h-126rpx w-126rpx flex items-center justify-center rounded-12rpx bg-hex-F5F3F0">
                <image
                  :src="item.itemImage"
                  mode="scaleToFill"
                  class="h-100rpx w-52rpx"
                />
              </div>
              <div class="w-65%">
                <div class="mb-8rpx text-28rpx font-600 text-hex-E0E0E0">{{ item.itemName }}</div>
                <div class="mb-12rpx flex items-center text-24rpx text-hex-E0E0E0">
                  <div>{{ item.specsDesc }}</div>
                </div>
                <div class="flex items-center justify-between">
                  <div class="text-28rpx font-bold text-hex-E0E0E0">¥{{ item.unitPrice }}</div>
                  <div class="flex items-center">
                    <image
                      :src="`${cdnUrl}/svgicons/userComment/reduce.svg${imgVersion}`"
                      mode="scaleToFill"
                      class="mt-5rpx h-50rpx w-50rpx"
                    />
                    <div class="ml-24rpx mr-14rpx text-hex-E0E0E0">{{ item.amount }}</div>
                    <image
                      :src="`${cdnUrl}/svgicons/userComment/add1.svg${imgVersion}`"
                      mode="scaleToFill"
                      class="mt-10rpx h-50rpx w-50rpx"
                    />
                  </div>
                </div>
              </div>
            </div>
          </uni-swipe-action-item>
        </uni-swipe-action>
      </div>
      <div v-if="propsDataList.length===0&&freezeGoodsList.length===0" class="flex flex-col items-center justify-center">
        <image
          :src="`${cdnUrl1}/imgs/xy/other/noneeattention.png${imgVersion}`"
          mode="scaleToFill"
          class="h-300rpx w-300rpx"
        />
        <div class="mb-64rpx text-28rpx text-hex-7C8699">暂无数据</div>
      </div>
      <div
        class="cardBoxShaow sticky bottom-0 left-0 right-0 box-border flex items-center justify-between rounded-200rpx bg-hex-ffffff p-14rpx">
        <div class="flex items-center">
          <div class="relative">
            <image
              :src="`${cdnUrl}/svgicons/home/goodsCar.svg${imgVersion}`"
              mode="scaleToFill"
              class="h-70rpx w-70rpx"
            />
            <div
              class="font-numberFont absolute right-0 box-border min-h-42rpx min-w-42rpx flex items-center justify-center border-2rpx border-hex-ffffff rounded-50% border-solid bg-hex-C1A670 text-24rpx text-hex-ffffff -top-30rpx">
              {{ selectLength }}
            </div>
          </div>
          <div
            class="text-28rpx font-bold text-hex-333333">
            预计金额:
            <text class="font-numberFont text-32rpx text-hex-ff4d4e">
              <text class="text-24rpx">¥</text>
              {{ totalPrice }}
            </text>
          </div>
        </div>
        <div
          class="addBoxShadow btn-theme-bg h-72rpx w-180rpx flex items-center justify-center rounded-82rpx text-28rpx text-hex-ffffff"
          @click="confirmOrder">
          去结算
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useAddressStore } from '@/stores/address'
import { useTeaStore } from '@/stores/tea'
import { useLoginStore } from '@/stores/login'

const props = defineProps<Props>()

const emits = defineEmits(['close', 'openDialog', 'delOpenDialog'])

const loginStore = useLoginStore()

let addressStores: any = useAddressStore()
let teaStores: any = useTeaStore()

const userStores = useUserStore()
interface storeIdT {
  storeId: any
}
interface Props {
  id: storeIdT
}
let options2: any = $ref([
  {
    text: '删除',
    style: {
      backgroundColor: '#E35757',
    },
  },
])
const swipeChange = (e, index) => {
  // console.log('返回：', e)
  // console.log('当前索引：', index)
}
const swipeClick = (e, index) => {
  let {
    content,
  } = e
  if (content.text === '删除') {
    emits('delOpenDialog', index)
    // uni.showModal({
    //   title: '提示',
    //   content: '是否删除',
    //   success: res => {
    //     if (res.confirm) {
    //       console.log('用户点击删除')
    //       propsDataList.splice(index, 1)
    //     } else if (res.cancel) {
    //       console.log('用户点击取消')
    //     }
    //   },
    // })
  } else {
    uni.showToast({
      title: `点击了${e.content.text}按钮`,
      icon: 'none',
    })
  }
}

let allGoodsItemIdList: any = $ref([])
// 获取购物车的数据
const getGoodsList = async () => {
  const reqData = {
    method: 'post',
    data: {
      'storeId': props.id,
      'trolleyType': 2,
    },
    headers: { UserId: userStores.user.id },
  }
  const { data, status, error } = await Fetch('/qqyapi/order/trolley/renderTrolleyViewDto', reqData)
  if (status !== 200 || data.code !== 0) {
    return
  }
  if (data.code === 0) {
    let allList: any = []
    allList = data?.result?.trolleyItemDescDTOList
    allGoodsItemIdList = []
    allList.forEach((item) => {
      allGoodsItemIdList.push(item.itemId)
    })
    propsDataList = data?.result?.trolleyItemDescDTOList
    propsDataList = propsDataList.filter((item) => {
      return item.freezeStatus === 0
    })
    freezeGoodsList = data?.result?.freezeItems
    // freezeGoodsList.forEach((item)=>{
    //   handleCancelSelect(item.itemId)
    // })
    totalPrice = data?.result?.settlePrice
    let filterList: any = []
    filterList = propsDataList.filter((item) => {
      return item.selectStatus === 0
    })
    selectLength = filterList.reduce((sum, item) => sum + item.amount, 0)
    let totalLength = propsDataList.reduce((sun, item) => sun + item.amount, 0)
    if (totalLength === selectLength) {
      if (selectLength === 0) {
        invertShow = false
        return
      }
      invertShow = true
    } else {
      invertShow = false
    }
  }
}

// 取消冻结项目的选中状态
const handelCancelfrezzStatus = async () => {
  const reqData = {
    method: 'post',
    data: {
      'storeId': props.id,
      'trolleyType': 2,
    },
    headers: { UserId: userStores.user.id },
  }
  const { status, data, error } = await Fetch('/qqyapi/order/trolley/confirmTrolleyStatus', reqData)
  if (status !== 200 || data.code !== 0) {
    return
  }
  if (data.code === 0) {
    getGoodsList()
    goConfirmOrder()
  }
}

const addGoodsNum = async (index) => {
  const reqData = {
    method: 'post',
    data: {
      'itemId': index,
      'trolleyType': 2,
    },
    headers: { UserId: userStores.user.id },
  }
  const { data, status, error } = await Fetch('/qqyapi/order/trolley/increaseItemAmount', reqData)
  if (status !== 200 || data.code !== 0) {
    return
  }
  if (data.code === 0) {
    getGoodsList()
  }
}
const reduceGoodsNum = useThrottleFn(async (index, num) => {
  let delFlag: any = 0
  if (num === 1) {
    delFlag = 1
  }
  const reqData = {
    method: 'post',
    data: {
      'delFlag': delFlag,
      'itemId': index,
      'trolleyType': 2,
    },
    headers: { UserId: userStores.user.id },
  }
  const { data, status, error } = await Fetch('/qqyapi/order/trolley/reduce', reqData)
  if (status !== 200 || data.code !== 0) {
    return
  }
  if (data.code === 0) {
    getGoodsList()
  }
}, 300)
let invertShow: any = $ref(false)
const handleInver = async () => {
  invertShow = !invertShow
  propsDataList.forEach((item: any) => {
    item.isSelect = invertShow
  })
  let selectFlag: any = 1
  if (invertShow) {
    selectFlag = 0
  }
  const reqData = {
    method: 'post',
    data: {
      'selectFlag': selectFlag,
      'trolleyType': 2,
    },
    headers: { UserId: userStores.user.id },
  }
  const { data, status, error } = await Fetch('/qqyapi/order/trolley/allSelectItemOperate', reqData)
  if (status !== 200 || data.code !== 0) {
    return
  }
  if (data.code === 0) {
    getGoodsList()
  }
}
const handleCancelSelect = async (index) => {
  const reqData = {
    method: 'post',
    data: {
      'itemId': index,
      'trolleyType': 2,
    },
    headers: { UserId: userStores.user.id },
  }
  const { data, status, error } = await Fetch('/qqyapi/order/trolley/unSelectItem', reqData)
  if (status !== 200 || data.code !== 0) {
    return
  }
  if (data.code === 0) {
    getGoodsList()
  }
}
const handleSelect = async (index) => {
  const reqData = {
    method: 'post',
    data: {
      'itemId': index,
      'trolleyType': 2,
    },
    headers: { UserId: userStores.user.id },
  }
  const { data, status, error } = await Fetch('/qqyapi/order/trolley/selectItem', reqData)
  if (status !== 200 || data.code !== 0) {
    return
  }
  if (data.code === 0) {
    getGoodsList()
  }
}

// 自提切换配送方式
const handelChangeSelectMethod = async () => {
  const reqData = {
    method: 'post',
    data: {
      'deliveryMethod': 2,
      'trolleyType': 2,
    },
    headers: { UserId: userStores.user.id },
  }
  const { status, data, error } = await Fetch('/qqyapi/order/trolley/setTrolleyDeliveryMethod', reqData)
}

// 外送切换配送方式
const changeOutwakeMethod = async (item) => {
  // 切换取餐方式调用接口
  const reqData = {
    method: 'post',
    data: {
      'deliveryMethod': 1,
      'trolleyType': 2,
      'userAddressId': item.id,
    },
    headers: { UserId: userStores.user.id },
  }
  const { status, data, error } = await Fetch('/qqyapi/order/trolley/setTrolleyDeliveryMethod', reqData)
}

let totalPrice: any = $ref(0)
let selectLength: any = $ref(0)

let propsDataList: any = $ref([])
let freezeGoodsList: any = $ref([])

let isGoOrder: any = $ref(true)
const goConfirmOrder = async () => {
  const reqData = {
    method: 'post',
    data: { 'storeId': props.id },
    headers: {
      AppType: 2,
      UserId: userStores.user.id,
    },
  }
  const { data, status, error } = await Fetch('/qqyapi/order/order/confirmOrder', reqData)
  if (status !== 200 || data.code !== 0) {
    return
  }
  if (data.code === 0) {
    navTo(`/pages-tea/comfirmOrder?storeId=${props.id}`)
  }
}
// 确认订单
const confirmOrder = async () => {
  if (!loginStore.roleId) {
    loginStore.setIsBack(true)
    loginStore.isGoLogin()
    return
  }
  let filterUnSelectList: any = [] //未选中
  filterUnSelectList = propsDataList.filter((item) => {
    return item.selectStatus === 1
  })
  // console.log(filterUnSelectList, 'filterUnSelectList')
  if (filterUnSelectList.length === propsDataList.length) {
    isGoOrder = false
    return
  }
  handelCancelfrezzStatus()
}
onMounted(() => {
  getGoodsList()
  if (addressStores.selfPickup === 0) {
    handelChangeSelectMethod()
  } else {
    changeOutwakeMethod(addressStores.selectData)
  }
})

const opendelpop = () => {
  emits('openDialog', allGoodsItemIdList)
}

const closeDlalog = () => {
  emits('close')
}
watchEffect(() => {
  uni.$on('singlgDel', async (item) => {
    const reqData = {
      method: 'post',
      data: {
        'delFlag': 1,
        'itemId': item,
        'trolleyType': 2,
      },
      headers: { UserId: userStores.user.id },
    }
    const { data, status, error } = await Fetch('/qqyapi/order/trolley/reduce', reqData)
    if (status !== 200 || data.code !== 0) {
      return
    }
    if (data.code === 0) {
      getGoodsList()
      uni.showToast({
        title: '删除成功',
        icon: 'none',
      })
    }
  })
  uni.$on('batchDel', async (itemList) => {
    const reqData = {
      method: 'post',
      data: {
        'trolleyType': 2,
      },
      headers: { UserId: userStores.user.id },
    }
    const { data, status, error } = await Fetch('/qqyapi/order/trolley/cleanTrolley', reqData)
    if (status !== 200 || data.code !== 0) {
      return
    }
    if (data.code === 0) {
      getGoodsList()
      uni.showToast({
        title: '删除成功',
        icon: 'none',
      })
    }
  })
  uni.$on('handelEvent', () => {
    getGoodsList()
  })
})
</script>

<route lang="json">
{"style":{"disableScroll":true}}
</route>

<style lang="scss">
.carbox{
  .teaGoodsCar{
    .addBoxShadow{
      box-shadow: 0rpx 6rpx 12rpx 0rpx rgb(76 131 40 / 25%);
    }

    .font-numberFont{
      font-family:'DingTalk JinBuTi';
    }
  }

  .cardBoxShaow{
    box-shadow: 0rpx 4rpx 20rpx 0rpx rgb(0 0 0 / 9%);
  }

  .scrolldemo{
    scrollbar-width: none; /* firefox */
    -ms-overflow-style: none; /* IE 10+ */
    overflow-x: hidden;
    overflow-y: auto;
  }

  .scrolldemo::-webkit-scrollbar {
    display: none; /* Chrome Safari */
  }

  .tagLine::after{
    position: absolute;
    content: '';
    height:14rpx;
    width:2rpx;
    top: 10rpx;
    right: -10rpx;
    background-color: #7c8699;
  }

  .tagLine:last-child::after{
    height:0rpx;
    width:0rpx;
  }

  ::v-deep(.uni-swipe_button){
    margin: 20px 0;
  }
}
</style>
